using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.XR;

public class ThirdPersonControllerPhysics : MonoBehaviour
{
    public float moveSpeed = 5f; // �ƶ��ٶ�
    public float rotationSpeed = 10f; // ��ת�ٶ�
    public float jumpForce = 5f; // ��Ծ����
    public LayerMask groundMask; // ����㼶���
    public Transform groundCheck; // �������
    public float groundDistance = 0.4f; // �����ⷶΧ
    private CharacterController controller; // 角色控制器
    private Rigidbody rb; // Rigidbody ���
    private bool isGrounded; // �Ƿ��ڵ�����
    private Vector3 moveDirection;
    public float gravityScale;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        Move();
        Jump();
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
        if (isGrounded)
        {
            Debug.Log("isground");
        }
        else
        {
            Debug.Log("notground");
        }

    }

    void Move()
    {
        // 获取输入
        float horizontal = Input.GetAxis("Horizontal"); // 左右
        float vertical = Input.GetAxis("Vertical"); // 前后

        // 计算移动方向
        Vector3 forward = Camera.main.transform.forward;
        Vector3 right = Camera.main.transform.right;

        forward.y = 0f;
        right.y = 0f;
        forward.Normalize();
        right.Normalize();

        moveDirection = (forward * vertical + right * horizontal).normalized * moveSpeed;

        // 应用重力
        if (!isGrounded)
        {
            moveDirection.y += Physics.gravity.y * gravityScale * Time.deltaTime; // 重力
            //Debug.Log("gravity");
        }
        else
        {
            moveDirection.y = 0; // 在地面时保持水平
        }

        // 使用 CharacterController 移动
        controller.Move(moveDirection * Time.deltaTime);

        // 调整角色朝向
        if (new Vector3(moveDirection.x, 0, moveDirection.z) != Vector3.zero)
        {
            Quaternion targetRotation = Quaternion.LookRotation(new Vector3(moveDirection.x, 0, moveDirection.z));
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }
    }


    void Jump()
    {
        // ������
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        // ����ڵ����ϲ�������Ծ��
        if (isGrounded && Input.GetButtonDown("Jump"))
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }
    }
}
